import shutil
import os
import re

digitslen = 2

def leadingzeros(num):
    num = str(num)
    while len(num) < digitslen:
        num = '0' + num
    return num

def fname_from_levelnum(levelnum):
    return "level_" + leadingzeros(levelnum) + ".txt"

def new_fname_after_inc(fname):
    levelnum = int(fname[6:6+digitslen])
    return "level_" + leadingzeros(levelnum + 1) + ".txt"

levelnum = input("Enter the level number you would like this new level to be: ")

if not levelnum.isdecimal() or len(levelnum) > digitslen:
    exit()
else:
    f = open("last_id.txt", "r");
    level_id = int(f.read()) + 1
    f.close()

    f = open("last_id.txt", "w");
    f.write(str(level_id))
    f.close()

    newfname = fname_from_levelnum(levelnum)
    
    fnames = [fname for fname in os.listdir(".") if re.match("level_" + ("[0-9]" * digitslen) + "\.txt", fname)]
    fnames.sort()
    fnames.reverse()
    for fname in fnames:
        if fname >= newfname:
            shutil.move(fname, new_fname_after_inc(fname))
        else:
            break

    f = open(newfname, "w")
    f.write(str(level_id) + """

<title>

<description>
---

<situation title>
"""

+ (((' ' * 10) + '\n') * 10) +

"""<max number of moves>
---

<statements>
MOVE UP
MOVE DOWN
MOVE LEFT
MOVE RIGHT
---

<program>
SUBPROGRAM START_HERE
---""")
    f.close()
